<template>
  <div class="cart">
    <el-card class="cart-card">
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><ShoppingCart /></el-icon>
            购物车
          </h2>
          <span class="cart-count">共 {{ cartList.length }} 件商品</span>
        </div>
      </template>
      
      <el-skeleton :loading="loading" animated :count="3">
        <template #default>
          <el-empty v-if="cartList.length === 0" description="购物车空空如也，快去逛逛吧~">
            <el-button type="primary" @click="$router.push('/products')">
              去购物
            </el-button>
          </el-empty>
          
          <div v-else>
            <!-- 全选和删除 -->
            <div class="cart-header">
              <el-checkbox
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              >
                全选
              </el-checkbox>
              <el-button
                type="danger"
                text
                :disabled="selectedItems.length === 0"
                @click="handleDeleteSelected"
              >
                删除选中
              </el-button>
            </div>
            
            <!-- 购物车列表 -->
            <div class="cart-list">
              <el-card
                v-for="item in cartList"
                :key="item.id"
                class="cart-item"
                shadow="never"
              >
                <div class="item-content">
                  <el-checkbox
                    :model-value="item.is_selected === 1"
                    @change="handleItemSelect(item)"
                  />
                  
                  <img
                    :src="item.product_image"
                    :alt="item.product_name"
                    class="item-image"
                    @click="$router.push(`/product/${item.product_id}`)"
                  />
                  
                  <div class="item-info">
                    <h4 class="item-name" @click="$router.push(`/product/${item.product_id}`)">
                      {{ item.product_name }}
                    </h4>
                    <span class="item-price">¥{{ item.product_price }}</span>
                  </div>
                  
                  <div class="item-quantity">
                    <el-input-number
                      :model-value="item.quantity"
                      :min="1"
                      :max="99"
                      @change="(val) => handleQuantityChange(item.id, val)"
                    />
                  </div>
                  
                  <div class="item-total">
                    <span class="total-price">
                      ¥{{ (item.product_price * item.quantity).toFixed(2) }}
                    </span>
                  </div>
                  
                  <div class="item-action">
                    <el-button
                      type="danger"
                      text
                      :icon="Delete"
                      @click="handleDeleteItem(item.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
            
            <!-- 结算栏 -->
            <el-card class="settlement-bar" shadow="always">
              <div class="settlement-content">
                <div class="settlement-left">
                  <el-checkbox
                    v-model="selectAll"
                    :indeterminate="isIndeterminate"
                    @change="handleSelectAll"
                  >
                    全选
                  </el-checkbox>
                  <el-button type="text" @click="handleClearCart">清空购物车</el-button>
                </div>
                
                <div class="settlement-right">
                  <div class="total-info">
                    <span>已选商品 <strong>{{ selectedItems.length }}</strong> 件</span>
                    <span class="total-label">合计：</span>
                    <span class="total-price">¥{{ totalPrice }}</span>
                  </div>
                  <el-button
                    type="danger"
                    size="large"
                    :disabled="selectedItems.length === 0"
                    @click="handleCheckout"
                  >
                    去结算
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </template>
      </el-skeleton>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import {
  updateCartItem,
  toggleCartItem,
  toggleAllCartItems,
  deleteCartItem,
  clearCart,
  deleteSelectedCartItems
} from '@/api/cart'
import { createOrder } from '@/api/order'
import { ShoppingCart, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const cartStore = useCartStore()

const loading = ref(true)

// 计算属性
const cartList = computed(() => cartStore.cartList)
const selectedItems = computed(() => cartStore.selectedItems)
const totalPrice = computed(() => cartStore.totalPrice)
const isAllSelected = computed(() => cartStore.isAllSelected)

// 全选状态
const selectAll = computed({
  get: () => isAllSelected.value,
  set: () => {}
})

// 半选状态
const isIndeterminate = computed(() => {
  return selectedItems.value.length > 0 && !isAllSelected.value
})

// 获取购物车列表
const fetchCartList = async () => {
  loading.value = true
  await cartStore.fetchCartList()
  loading.value = false
}

// 全选/取消全选
const handleSelectAll = async (value) => {
  try {
    await toggleAllCartItems({ selected: value })
    await fetchCartList()
  } catch (error) {
    console.error('操作失败：', error)
  }
}

// 单个商品选中
const handleItemSelect = async (item) => {
  try {
    await toggleCartItem(item.id, item.is_selected)
    await fetchCartList()
  } catch (error) {
    console.error('操作失败：', error)
  }
}

// 修改数量
const handleQuantityChange = async (id, quantity) => {
  try {
    await updateCartItem(id, { quantity })
    await fetchCartList()
    ElMessage.success('修改成功')
  } catch (error) {
    console.error('修改数量失败：', error)
  }
}

// 删除商品
const handleDeleteItem = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCartItem(id)
    await fetchCartList()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
    }
  }
}

// 删除选中商品
const handleDeleteSelected = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 件商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteSelectedCartItems()
    await fetchCartList()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
    }
  }
}

// 清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await clearCart()
    await fetchCartList()
    ElMessage.success('购物车已清空')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败：', error)
    }
  }
}

// 去结算
const handleCheckout = () => {
  // 这里应该跳转到订单确认页面，为了简化，我们直接创建订单
  ElMessageBox.prompt('请输入收货地址（格式：姓名,手机号,地址）', '确认订单', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPlaceholder: '例如：张三,13800138000,北京市朝阳区xxx街道',
    inputValidator: (value) => {
      if (!value) {
        return '请输入收货地址'
      }
      const parts = value.split(',')
      if (parts.length !== 3) {
        return '请按格式输入：姓名,手机号,地址'
      }
      return true
    }
  }).then(async ({ value: addressInput }) => {
    try {
      // 解析地址信息
      const [name, phone, address] = addressInput.split(',').map(s => s.trim())
      
      // 准备订单数据
      const products = selectedItems.value.map(item => ({
        product_id: item.product_id,
        quantity: item.quantity
      }))
      
      // 调用创建订单接口
      await createOrder({
        products,
        address: {
          receiver_name: name,
          receiver_phone: phone,
          receiver_address: address
        }
      })
      
      ElMessage.success('订单创建成功')
      
      // 刷新购物车（后端已清空选中商品）
      await fetchCartList()
      
      // 跳转到订单页面
      router.push('/orders')
    } catch (error) {
      console.error('创建订单失败：', error)
      ElMessage.error(error.response?.data?.message || '创建订单失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

onMounted(() => {
  fetchCartList()
})
</script>

<style scoped>
.cart {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.cart-count {
  color: #999;
  font-size: 14px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.cart-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.cart-item {
  border: 1px solid #eee;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.item-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-name:hover {
  color: #e3393c;
}

.item-price {
  color: #999;
  font-size: 14px;
}

.item-quantity {
  flex-shrink: 0;
}

.item-total {
  width: 120px;
  text-align: right;
  flex-shrink: 0;
}

.total-price {
  font-size: 18px;
  color: #e3393c;
  font-weight: bold;
}

.item-action {
  flex-shrink: 0;
}

.settlement-bar {
  position: sticky;
  bottom: 0;
  margin-top: 20px;
  background: white;
  z-index: 100;
}

.settlement-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settlement-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.settlement-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  display: flex;
  align-items: baseline;
  gap: 10px;
}

.total-info strong {
  color: #e3393c;
}

.total-label {
  font-size: 16px;
  margin-left: 10px;
}

.total-info .total-price {
  font-size: 24px;
  color: #e3393c;
  font-weight: bold;
}

/* 响应式 */
@media (max-width: 768px) {
  .item-content {
    flex-wrap: wrap;
  }
  
  .item-image {
    width: 80px;
    height: 80px;
  }
  
  .item-total {
    width: auto;
  }
  
  .settlement-content {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .settlement-left,
  .settlement-right {
    justify-content: space-between;
    width: 100%;
  }
}
</style>





